package com.google.code.swingonfire.component;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;

import com.google.code.swingonfire.builder.JButtonBuilder;
import com.google.code.swingonfire.builder.JTextFieldBuilder;

public class JFileField extends JComponent
{

    private static final long serialVersionUID = -109065928088996069L;

    private final JTextField fileField;
    private final JButton browseButton;
    private final JFileChooser fileChooser;

    public JFileField()
    {
        super();

        setLayout(new BorderLayout(8, 0));

        fileField = new JTextFieldBuilder().build();

        browseButton = new JButtonBuilder().text("Browse...").opaque(false).listener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                browse();
            }

        }).build();

        fileChooser = new JFileChooser();

        add(fileField, BorderLayout.CENTER);
        add(browseButton, BorderLayout.EAST);
    }

    public void setFileFilter(FileNameExtensionFilter filter)
    {
        fileChooser.setFileFilter(filter);
    }

    public void browse()
    {
        String path = fileField.getText();
        File file = new File(path);

        while ((file != null) && (!file.exists()))
        {
            path = file.getParent();
            file = (path != null) ? new File(path) : null;
        }

        if (file != null)
        {
            fileChooser.setSelectedFile(file);
        }

        //        FileNameExtensionFilter filter = new FileNameExtensionFilter(
        //            "JPG & GIF Images", "jpg", "gif");
        //        chooser.setFileFilter(filter);
        int returnVal = fileChooser.showOpenDialog(SwingUtilities.getWindowAncestor(this));

        if (returnVal == JFileChooser.APPROVE_OPTION)
        {
            fileField.setText(fileChooser.getSelectedFile().toString());
        }
    }

    public File getFile()
    {
        return new File(fileField.getText());
    }

    public void setFile(File value)
    {
        fileField.setText((value != null) ? value.getAbsolutePath() : null);
    }
}
